<?php
namespace WechatSDK\Components;

use WechatSDK\Lib\Tools;
require_once ('Common.php');

/**
 * 微信网页授权组件
 * @author guibinyu
 * @date 2017-06-15 04:14:50
 */
class Oauth extends Common
{

     const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
    const OAUTH_AUTHORIZE_URL = '/authorize?';
    const OAUTH_TOKEN_URL = '/sns/oauth2/access_token?';
    const OAUTH_REFRESH_URL = '/sns/oauth2/refresh_token?';
    const OAUTH_USERINFO_URL = '/sns/userinfo?';
    const OAUTH_AUTH_URL = '/sns/auth?';
    
	function __construct($appid,$secret,$token)
	{
        parent::__construct($appid,$secret,$token);
	}

	function __destruct()
	{
	}
     /**
     *  授权跳转接口
     * @param string $callback 授权回跳地址
     * @param string $state 为重定向后会带上state参数（填写a-zA-Z0-9的参数值，最多128字节）
     * @param string $scope 授权类类型(可选值snsapi_base|snsapi_userinfo)
     * @return string
     */
    public function getRedirect($callback, $state = '', $scope = 'snsapi_userinfo') {
        $redirect_uri = urlencode($callback);
        $result = self::OAUTH_PREFIX . self::OAUTH_AUTHORIZE_URL . "appid={$this->appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
        return $result;
    }
     /**
     * 通过 code 获取授权access_token
     * @return bool|array
     */
    public function getAccessToken($code='') {
        $result = Tools::httpGet(self::API_BASE_URL_PREFIX . self::OAUTH_TOKEN_URL . "appid={$this->appid}&secret={$this->secret}&code={$code}&grant_type=authorization_code");
        $result = $this->parsing($result);
        return $result;
    }
    /**
     * 刷新access token并续期
     * @param string $refresh_token
     * @return bool|array
     */
    public function getRefreshToken($refresh_token) {
        $result = Tools::httpGet(self::API_BASE_URL_PREFIX . self::OAUTH_REFRESH_URL . "appid={$this->appid}&grant_type=refresh_token&refresh_token={$refresh_token}");
         $result = $this->parsing($result);
        return $result;
    }
	 /**
     * 获取授权后的用户资料
     * @param string $access_token
     * @param string $openid
     * @return bool|array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
     * 注意：unionid字段 只有在用户将公众号绑定到微信开放平台账号后，才会出现。建议调用前用isset()检测一下
     */
    public function getUserInfo($access_token, $openid) {
        $result = Tools::httpGet(self::API_BASE_URL_PREFIX . self::OAUTH_USERINFO_URL . "access_token={$access_token}&openid={$openid}");
         $result = $this->parsing($result);
        return $result;
    }

}
?>